package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.MsgConfig;
import com.wondertek.poms.core.service.IContentBlackService;
import com.wondertek.poms.core.service.IContentService;
import com.wondertek.poms.core.service.IProductInfoPackageService;
import com.wondertek.poms.dao.po.*;
import com.wondertek.poms.dao.repo.IContentBlackDao;
import com.wondertek.poms.dao.repo.IContentWhiteDao;
import com.wondertek.poms.dao.repo.IPrdContDao;
import com.wondertek.poms.dao.vo.ContentBlackVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p><b>ContentBlackServiceImpl Description:</b> 黑名单表service层实现 </p>
 * @author 窦再兴
 * <p><b>DATE</b> 2020-12-03 10:19:26</p>
 */
@Service
@Scope("prototype")
public class ContentBlackServiceImpl extends ServiceImpl<ContentBlack, Long> implements IContentBlackService {

	@Autowired
	private IContentService contentService;
	@Autowired
	private IProductInfoPackageService productInfoPackageService;
	@Autowired
	private IContentWhiteDao contentWhiteDao;
	@Autowired
	private IContentBlackDao contentBlackDao;
	@Autowired
	private IPrdContDao prdContDao;
	@Autowired
	private MsgConfig msgConfig;
	@PersistenceContext
    public EntityManager em;

	@Override
	@Transactional
	public ContentBlack deleteLogic(Long id) {
		ContentBlack cp = jpaRepository.getOne(id);
		ContentBlack.putTimeAndUser(cp);
		cp.setDeleted(Constants.DELETE_1);
		jpaRepository.save(cp);
		return cp;
	}

	@Override
	@Transactional
	public ContentBlack merge(ContentBlack model) {
		ContentBlack.putTimeAndUser(model);
		ContentBlack dbo = jpaRepository.getOne(model.getId());
		CopyUtils.copyProperties(model, dbo);
		return jpaRepository.save(dbo);
	}

	@Override
	public Page<ContentBlackVo> findPage(ContentBlackVo contentBlackVo, int page, int rows, String sidx, String sord) {
		String condition = sqlStringWhere(true,contentBlackVo);
		Object o = em.createNativeQuery(condition).getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = PageRequest.of(page - 1, rows);
		if(count>0){
			condition=sqlStringWhere(false,contentBlackVo);
			Query query=em.createNativeQuery(condition);
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<Object[]> list=query.getResultList();
			List<ContentBlackVo> contentBlacklist=toContentBlacklist(list);;
			PageImpl<ContentBlackVo> result=new PageImpl<ContentBlackVo>(contentBlacklist,pageable,count);
			em.close();
			return result;
		}
		em.close();
		return  Page.empty(pageable);
	}

	@Override
	public ResultBean saveOne(ContentBlackVo contentBlackVo) {
		ContentBlack contentBlack = new ContentBlack();
		BeanUtils.copyProperties(contentBlackVo, contentBlack);
		if(StringUtils.isBlank(contentBlackVo.getContentName())){
			Content content0=new Content();
			content0.setContentId(contentBlackVo.getContentId());
			List<Content> list=contentService.findAll(content0);
			if(list!=null && list.size()>0){
				Content content=list.get(0);
				if(content!=null && StringUtils.isNotBlank(content.getName())){
					//目标商品包 不能有 该内容id的正常节目
					List<PrdCont> prdContList=prdContDao.findPcByContentIdInPrdInfo(contentBlackVo.getContentId(), contentBlackVo.getPrdInfoId());
					System.out.println(prdContList.size());
					if(prdContList.size()>0){
						return ResultBean.error("该内容id在该商品包已有存在节目");
					}
					contentBlack.setContentName(content.getName());
				}
			}else{
				return ResultBean.error("该内容id在本平台不存在");
			}
		}
		Map<String,String> judgeMap=isRepeat(contentBlackVo,0);
		//该内容对应的商品包的黑名单已存在
		if(StringUtils.isNotBlank(judgeMap.get("1"))) {
			return ResultBean.error(msgConfig.getBlacklistAlreadyExisted());
			//该内容对应的商品包的白名单已存在
		}else if(StringUtils.isNotBlank(judgeMap.get("2"))){
			return ResultBean.error(msgConfig.getWhitelistAlreadyExisted());
		}
		if(contentBlack.getPackageId()!=null && StringUtils.isBlank(contentBlack.getPackageName())){
			ProductInfoPackage productInfoPackage =productInfoPackageService.get(contentBlack.getPackageId());
			if(productInfoPackage!=null){
				contentBlack.setPackageName(productInfoPackage.getProductInfoPackageName());
			}
		}
		ContentBlack.putTimeAndUser(contentBlack);
		save(contentBlack);
		return ResultBean.ok();
	}

	@Override
	public Map<String,String> isRepeat(ContentBlackVo contentBlackVo,int judge) {
		Map<String,String> map=new HashMap<>(1);
		String contentId=contentBlackVo.getContentId();
		Long prdInfoId=contentBlackVo.getPrdInfoId();
		int blackCount = contentBlackDao.findCountByContentIdAndPackageId(contentId,prdInfoId);
		if (blackCount>0) {
			map.put("1","1");
		}else{
			//白名单
			if(judge==1){
				//如果该商品包有二级产品,且该二级产品下有别的商品包
				List<ContentWhite> whiteList = contentWhiteDao.findCountByContentIdAndPrdInfoPackageId(contentId,prdInfoId);
				if(whiteList.size()>0){
					map.put("22","");
					map.put("21",whiteList.get(0).getPackageId()+":《"+whiteList.get(0).getPackageName()+"》");
					for (ContentWhite contentWhite:whiteList) {
						map.put("22",map.get("22")+","+contentWhite.getPrdInfoId()+":《"+contentWhite.getPrdInfoName()+"》");
					}
					return map;
				}
			}
			int whiteCount = StringUtil.stringToInteger(contentWhiteDao.findCountByContentIdAndPackageId(contentId,prdInfoId).toString());
			if (whiteCount>0) {
				map.put("2","2");
			}
		}
		return map;
	}

	List<ContentBlackVo> toContentBlacklist(List<Object[]> list){
		List<ContentBlackVo> contentBlacklist=new ArrayList<>();
			for (Object[] obj:list){
				ContentBlackVo contentBlack=new ContentBlackVo();
				contentBlack.setContentId (StringUtil.null2Str(obj[0]));
				contentBlack.setPackageId(StringUtil.nullToLong(obj[1]));
				contentBlack.setPrdInfoId (StringUtil.nullToLong(obj[2]));
				contentBlack.setRemarks(StringUtil.null2Str(obj[3]));
				contentBlack.setCreatedBy (StringUtil.null2Str(obj[4]));
				contentBlack.setCreatedTime(StringUtil.null2Str(obj[5]));
				contentBlack.setUpdatedTime(StringUtil.null2Str(obj[6]));
				contentBlack.setContentName (StringUtil.null2Str(obj[7]));
				contentBlack.setPackageName (StringUtil.null2Str(obj[8]));
				contentBlack.setPrdInfoName (StringUtil.null2Str(obj[9]));
				contentBlack.setId (StringUtil.nullToLong(obj[10]));
				contentBlacklist.add(contentBlack);
			}
		return contentBlacklist;
	}

	public String sqlStringWhere(boolean getCount, ContentBlackVo contentBlackVo) {
		StringBuilder condition = new StringBuilder();
		if (getCount) {
			condition.append("select count(0) ");
		} else {
			condition.append("select CONTENT_ID,PACKAGE_ID,PRD_INFO_ID,REMARKS,CREATED_BY,to_char(CREATED_TIME,'YYYY-MM-DD HH24:MI:SS'),to_char(UPDATED_TIME,'YYYY-MM-DD HH24:MI:SS') ,CONTENT_NAME,PACKAGE_NAME,PRD_INFO_NAME,ID ");
		}
		condition.append(" from CONTENT_BLACK where deleted =0 ");
		if (contentBlackVo != null) {
			if (StringUtils.isNotBlank(contentBlackVo.getContentId())) {
				condition.append(" and CONTENT_ID = " + contentBlackVo.getContentId());
			}
			if (contentBlackVo.getPackageId() != null) {
				condition.append(" and PACKAGE_ID = " + contentBlackVo.getPackageId());
			}
			if (contentBlackVo.getPrdInfoId() != null) {
				condition.append(" and PRD_INFO_ID = " + contentBlackVo.getPrdInfoId());
			}

			if (StringUtils.isNotBlank(contentBlackVo.getCreatedStartTime())) {
				condition.append(" and CREATED_TIME > TO_DATE('" + contentBlackVo.getCreatedStartTime() + "', 'yyyy-MM-dd HH24:MI:SS')");
			}
			if (StringUtils.isNotBlank(contentBlackVo.getCreatedEndTime())) {
				condition.append(" and CREATED_TIME <= TO_DATE('" + contentBlackVo.getCreatedEndTime() + "', 'yyyy-MM-dd HH24:MI:SS')+1");
			}
		}
		condition.append(" order by CREATED_TIME desc ");
		return condition.toString();
	}
}